package com.example.design.beautiful.unit_test.interface_auth_fun;


public class DefaultApiAuthenticator implements ApiAuthenticator {
    CredentialStorage credentialStorage;

    public DefaultApiAuthenticator() {
        this.credentialStorage = new MysqlCredentialStorage();
    }

    public DefaultApiAuthenticator(CredentialStorage credentialStorage) {
        this.credentialStorage = credentialStorage;
    }

    @Override
    public void auth(String url) {
        ApiRequest apiRequest = ApiRequest.createFromFullUrl(url);
        auth(apiRequest);
    }

    @Override
    public void auth(ApiRequest apiRequest) {
        String appId = apiRequest.getAppId();
        String token = apiRequest.getToken();
        long timestamp = apiRequest.getTimeStamp();
        String baseUrl = apiRequest.getBaseUrl();
        // 客户端token
        AuthToken clientAuthToken = new AuthToken(token, timestamp);
        if (clientAuthToken.isExpired()) {
            throw new RuntimeException("Token is expired.");
        }
        // 服务端token
        String password = credentialStorage.getPassWordByApppId(appId);
        AuthToken serverAuthToken = AuthToken.create(baseUrl, timestamp, password, appId);
        if (!serverAuthToken.isMatch(clientAuthToken)) {
            throw new RuntimeException("Token verfication failed.");
        }
    }
}
